package com.sp2p.action.front;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.gofull.gateway.wechat.config.WechatConfig;
import com.gofull.gateway.wechat.util.WechatUtils;
import com.shove.Convert;
import com.shove.util.JSONUtils;
import com.shove.util.SqlInfusion;
import com.shove.util.UtilDate;
import com.shove.web.util.DesSecurityUtil;
import com.sp2p.constants.IConstants;
import com.sp2p.entity.Avatar;
import com.sp2p.entity.User;
import com.sp2p.service.GameService;
import com.sp2p.service.MyHomeService;
import com.sp2p.service.UserService;
import com.sp2p.util.RandomWeightUtil;
import com.shove.util.StringUtils;

public class GameAction extends BaseFrontAction {
	public static Log log = LogFactory.getLog(GameAction.class);
	private static final long serialVersionUID = 1L;

	private GameService gameService;
	protected UserService userService;
	private MyHomeService myHomeService;

	public MyHomeService getMyHomeService() {
		return myHomeService;
	}

	public void setMyHomeService(MyHomeService myHomeService) {
		this.myHomeService = myHomeService;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public GameService getGameService() {
		return gameService;
	}

	public void setGameService(GameService gameService) {
		this.gameService = gameService;
	}

	public String gameLottery() throws Exception {
		// List<Map<String, Object>> lotteryAwardList =
		// gameService.queryLotteryAward(1);
		// request().setAttribute("lotteryAwardList", lotteryAwardList);
		//		
		// int chanceNum = 0;
		// User user = this.getUser();
		// Long userId = user.getId();
		// if (userId != null){
		// Map<String, String> userMap =
		// gameService.queryLotteryUserInfo(userId,1);
		// if(userMap != null && userMap.size() > 0){
		// chanceNum = Convert.strToInt(userMap.get("chanceNum"), 0);
		// }
		// }
		// request().setAttribute("chanceNum", chanceNum);

		return SUCCESS;
	}

	/**
	 * 大转盘游戏
	 * 
	 * @throws Exception
	 */
	public void gameLotteryPlay() throws Exception {
		JSONObject obj = new JSONObject();
		obj.put("msg", "LOT04");
		JSONUtils.printObject(obj);
		return;

		// User user = this.getUser();
		// Long userId = user.getId();
		// if (userId == null){
		// obj.put("msg","noLogin");
		// JSONUtils.printObject(obj);
		// return;
		// }
		//		
		// //参与游戏用户信息
		// Map<String, String> userMap =
		// gameService.queryLotteryUserInfo(userId,1);
		// if(userMap == null || userMap.size() <= 0){
		// obj.put("msg", "noChance");
		// JSONUtils.printObject(obj);
		// return;
		// }
		//		
		// int chanceNum = Convert.strToInt(userMap.get("chanceNum"), 0);
		// if (chanceNum <= 0 ){
		// obj.put("msg", "noChance");
		// JSONUtils.printObject(obj);
		// return;
		// }
		//		
		// //获奖次数作为权重的基础除数
		// double baseNum = Convert.strToDouble(userMap.get("awardNum"), 0) * 2;
		// baseNum = (baseNum == 0 ? 1.0 : baseNum);
		//		 
		// //权重初始化
		// List<Map<String, Object>> lotteryGiftList =
		// gameService.queryLotteryGift(1);
		// ArrayList<Avatar> list = new ArrayList<Avatar>();
		// double noAwardWeight = 100.0;
		// if (lotteryGiftList != null) {
		// for (Map<String, Object> map : lotteryGiftList) {
		// String key = map.get("lotteryIndex").toString();
		// Double weight = Convert.strToDouble(map.get("weight").toString(), 0)
		// / baseNum;
		// list.add(new Avatar(key, weight));
		// noAwardWeight = noAwardWeight - weight;
		// }
		// }else{
		// obj.put("msg","LOT04");
		// JSONUtils.printObject(obj);
		// return;
		// }
		// //谢谢参与权重为100-sum(奖品权重)
		// list.add(new Avatar("11", noAwardWeight));
		//		
		// //获取中奖位置
		// Avatar[] result = RandomWeightUtil.getRandomN(list, 1);
		// int prize = Convert.strToInt(result[0].key, -1);
		//        
		// //数据实际操作
		// long r = -1L;
		// r = gameService.gameLotteryPlay(userId, 1, prize);
		//        
		// if(r < 0){
		// obj.put("msg","LOT04");
		// JSONUtils.printObject(obj);
		// return;
		// }
		//        
		// obj.put("msg", "success");
		// obj.put("prize", prize);
		// JSONUtils.printObject(obj);
	}

	/**
	 * 打狼游戏
	 * 
	 * @throws Exception
	 */
	public void gameSheepMWGetAward() throws Exception {
		JSONObject obj = new JSONObject();

		String mobilePhone = Convert
				.strToStr(paramMap.get("mobilePhone"), null);

		// 参与游戏用户奖励信息
		Map<String, String> awardMap = gameService
				.querySheepMWAward(mobilePhone);
		Map<String, String> userMap = userService
				.queryUserByUserName(mobilePhone);
		if (awardMap == null || awardMap.size() <= 0) {
			if (null == userMap || userMap.size() <= 0) {
				// 新用户增加新手红包
				gameService.insertSheepMWAward(mobilePhone, 1, 2888.00, 0);
				obj.put("awardAmount", "2888.00");
				obj.put("awardStatus", "0"); // 奖励兑现状态（0：未兑现 1：已兑现）
				obj.put("awardType", "1"); // 奖励类型（1：新手红包 2：现金红包）
			} else {
				int max = 2;
				int min = 1;
				Random random = new Random();
				double dealMoney = (double) (random.nextInt(max)
						% (max - min + 1) + min);

				// 老用户增加现金红包
				gameService.insertSheepMWAward(mobilePhone, 2, dealMoney, 0);

				obj.put("awardAmount", dealMoney + "");
				obj.put("awardStatus", "0"); // 奖励兑现状态（0：未兑现 1：已兑现）
				obj.put("awardType", "2"); // 奖励类型（1：新手红包 2：现金红包）
			}
		} else {
			if (null == userMap || userMap.size() <= 0) {
				obj.put("awardAmount", awardMap.get("awardAmount"));
				obj.put("awardStatus", awardMap.get("awardStatus"));
				obj.put("awardType", awardMap.get("awardType"));
			} else {
				obj.put("awardStatus", "1"); // 奖励兑现状态（0：未兑现
				// 1：已兑现）现金奖励，3月17日统一兑现
			}
		}

		JSONUtils.printObject(obj);
	}

	/**
	 * 分裂红包游戏
	 * 
	 * @return
	 * @throws Exception
	 */
	public String wlcShare() throws Exception {
		// 微信公众号接口
		Map<String, String> wxConfigMap = WechatUtils.jSdkConfig(request());
		request().setAttribute("wxConfigMap", wxConfigMap);

		return SUCCESS;
	}

	public void wlcShareInit() throws Exception {
		JSONObject obj = new JSONObject();

		obj.put("msg", "envelopeEnd");

		// User user = this.getUser();
		// Long userId = user.getId();
		// int isBindMobile = user.getIsBindMobile();
		// if (userId == null){
		// obj.put("msg","noLogin");
		// JSONUtils.printObject(obj);
		// return;
		// }
		//		
		// if(isBindMobile == 0){
		// obj.put("msg","noBindMobile");
		// JSONUtils.printObject(obj);
		// return;
		// }
		//		
		// String username = user.getUserName();
		// Long senvId = -1L;
		// int isDead = 0;
		// Map<String, String> spliteEnvelopeMap =
		// gameService.querySpliteEnvelopeByUserId(userId);
		// if(spliteEnvelopeMap != null && spliteEnvelopeMap.size() > 0){
		// senvId = Convert.strToLong(spliteEnvelopeMap.get("id"), -1L) ;
		// isDead = Convert.strToInt(spliteEnvelopeMap.get("isDead"), 0);
		// }else{
		// obj.put("msg","noSpliteEnvelope");
		// JSONUtils.printObject(obj);
		// return;
		// }
		// //红包已过期
		// if(isDead == 1){
		// obj.put("msg","spliteEnvelopeDead");
		// JSONUtils.printObject(obj);
		// return;
		// }
		//	    
		// DesSecurityUtil des = new DesSecurityUtil();
		// String encParam = des.encrypt(senvId + "|" + username);
		// obj.put("param", encParam);
		//	    
		// obj.put("msg", "success");
		JSONUtils.printObject(obj);
	}

	// public String wlcShareInfo() throws Exception {
	// // String param = request("param");
	// //
	// // DesSecurityUtil des = new DesSecurityUtil();
	// // String[] deParam = des.decrypt(param).split("\\|");
	// // Long senvId = Convert.strToLong(deParam[0], -1L);
	// // String username = deParam[1];
	// //
	// // List<Map<String, Object>> spliteEnvelopeTreeList = gameService
	// // .querySpliteEnvelopeTree(senvId);
	// // Map<String, String> sEnvelopeTreeShareMap = gameService
	// // .querySETreeShareInfo(senvId);
	// //
	// // request().setAttribute("username", username);
	// // request()
	// // .setAttribute("spliteEnvelopeTreeList", spliteEnvelopeTreeList);
	// // request().setAttribute("sEnvelopeTreeShareMap",
	// sEnvelopeTreeShareMap);
	// //
	// // // 微信公众号接口
	// // Map<String, String> wxConfigMap = WechatUtils.jSdkConfig(request());
	// // request().setAttribute("wxConfigMap", wxConfigMap);
	// // return SUCCESS;
	// }

	public void wlcShareReceive() throws Exception {
		// JSONObject obj = new JSONObject();
		//
		// String senvKey =
		// SqlInfusion.FilteSqlInfusion(paramMap.get("senvKey"));
		// DesSecurityUtil des = new DesSecurityUtil();
		// String[] deParam = des.decrypt(senvKey).split("\\|");
		// Long senvId = Convert.strToLong(deParam[0], -1L);
		// String username = deParam[1];
		// String mobilePhone = SqlInfusion.FilteSqlInfusion(paramMap
		// .get("mobilePhone"));
		// double valMoney = 0d;
		//
		// Map<String, String> spliteEnvelopeMap = gameService
		// .querySpliteEnvelopeById(senvId);
		// int isDead = 0;
		// if (spliteEnvelopeMap != null && spliteEnvelopeMap.size() > 0) {
		// isDead = Convert.strToInt(spliteEnvelopeMap.get("isDead"), 0);
		// }
		// // 红包已过期
		// if (isDead == 1) {
		// obj.put("msg", "spliteEnvelopeDead");
		// JSONUtils.printObject(obj);
		// return;
		// }
		//
		// Map<String, String> sEnvelopeTreeMap = gameService.querySETreeInfo(
		// senvId, mobilePhone);
		// if (sEnvelopeTreeMap != null && sEnvelopeTreeMap.size() > 0) {
		// // 已领取
		// obj.put("receivedStatus", sEnvelopeTreeMap.get("receivedStatus"));
		// obj.put("valMoney", sEnvelopeTreeMap.get("valMoney"));
		// obj.put("msg", "hasReceived");
		// JSONUtils.printObject(obj);
		// return;
		// }
		//
		// // 随机获取体验金金额
		// valMoney = getvalMoney(senvId, mobilePhone);
		// if (valMoney == 0) {
		// // 已领完
		// obj.put("msg", "isOver");
		// JSONUtils.printObject(obj);
		// return;
		// } else if (valMoney < 0) {
		// // 超过限额
		// obj.put("msg", "LimitExceeded");
		// JSONUtils.printObject(obj);
		// return;
		// }
		//
		// // 获取红包
		// long res = gameService.spliteEnvelopeToElite(senvId, valMoney,
		// mobilePhone);
		// if (res < 0) {
		// obj.put("msg", "fail");
		// JSONUtils.printObject(obj);
		// return;
		// }
		//
		// Map<String, String> userMap = userService
		// .queryUserBymobilePhone(mobilePhone);
		// if (userMap != null && userMap.size() > 0
		// && !userMap.get("username").equals(username)) {
		// obj.put("msg", "success");
		// } else {
		// obj.put("msg", "register");
		// }
		//
		// obj.put("valMoney", valMoney);
		// JSONUtils.printObject(obj);
	}

	private double getvalMoney(Long senvId, String mobilePhone)
			throws Exception {
		double valMoney = 0d;
		Map<String, String> sEnvelopeTreeRemainMap = gameService
				.querySETreeRemainById(senvId);
		double remainSum = Convert.strToDouble(sEnvelopeTreeRemainMap
				.get("remainSum"), 0);
		Map<String, String> envelopeRemainMap = gameService
				.queryEnvelopeRemainByPhone(mobilePhone);
		double envelopeRemainSum = Convert.strToDouble(envelopeRemainMap
				.get("envelopeRemainSum"), 0);
		double remain = remainSum > envelopeRemainSum ? envelopeRemainSum
				: remainSum;
		int max = 1000;
		int min = 100;
		if (remainSum <= 0) {
			valMoney = 0;
		} else if (envelopeRemainSum <= 0) {
			valMoney = -1;
		} else if (max >= remain) {
			valMoney = remain;
		} else {
			Random random = new Random();
			valMoney = (double) (random.nextInt(max) % (max - min + 1) + min);
		}

		return valMoney;
	}

	public void isSpliteEnvelope() throws Exception {
		JSONObject obj = new JSONObject();
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			obj.put("msg", "noLogin");
			JSONUtils.printObject(obj);
			return;
		}

		int isDead = 0;
		long senvId = -1L;
		Map<String, String> spliteEnvelopeMap = gameService
				.querySpliteEnvelopeByUserId(userId);
		if (spliteEnvelopeMap != null && spliteEnvelopeMap.size() > 0) {
			senvId = Convert.strToLong(spliteEnvelopeMap.get("id"), -1L);
			isDead = Convert.strToInt(spliteEnvelopeMap.get("isDead"), 0);
		} else {
			obj.put("msg", "noSpliteEnvelope");
			JSONUtils.printObject(obj);
			return;
		}

		// 红包已过期
		if (isDead == 1) {
			obj.put("msg", "spliteEnvelopeDead");
			JSONUtils.printObject(obj);
			return;
		}

		String username = user.getUserName();
		DesSecurityUtil des = new DesSecurityUtil();
		String encParam = des.encrypt(senvId + "|" + username);
		obj.put("param", encParam);

		obj.put("msg", 1);
		JSONUtils.printObject(obj);
	}

	/**
	 * 掀盖头游戏
	 * 
	 * @throws Exception
	 */
	public String xianGTInit() throws Exception {
		// String code = request("code");
		// if(null == code || "".equals(code)){
		// return "failed";
		// }
		//		
		// Map<String, String> map = WechatUtils.getOauth2AccessToken(
		// WechatConfig.APPID, WechatConfig.APPSECRET, code);
		// int errcode = Convert.strToInt(map.get("errcode"), 0);
		// String openid = Convert.strToStr(map.get("openid"), "");
		// if (errcode > 0 || "".equals(openid)) {
		// return "failed";
		// }
		//		
		// session().setAttribute("openid", openid);
		// //微信公众号JSSDK接口初始化
		// Map<String,String> wxConfigMap = WechatUtils.jSdkConfig(request());
		// request().setAttribute("wxConfigMap", wxConfigMap);

		return SUCCESS;
	}

	public void myPrizeXianGt() throws Exception {
		JSONObject obj = new JSONObject();
		String openid = session().getAttribute("openid") == null ? ""
				: session().getAttribute("openid").toString();
		if ("".equals(openid)) {
			return;
		}

		Map<String, String> voucherCodeMap = gameService
				.queryVoucherCodeByOpenid(openid);
		if (null == voucherCodeMap) {
			obj.put("award", "0");
			JSONUtils.printObject(obj);
		} else {
			HashMap<String, String> awardMap = new HashMap<String, String>();
			awardMap.put("100.00", "1");
			awardMap.put("50.00", "2");
			awardMap.put("30.00", "3");
			awardMap.put("20.00", "4");
			awardMap.put("10.00", "5");

			obj.put("award", awardMap.get(voucherCodeMap.get("valMoney")));
			obj.put("prizecode", voucherCodeMap.get("paycode"));
			JSONUtils.printObject(obj);
			session().setAttribute("paycode", voucherCodeMap.get("paycode"));
		}
	}

	public void xianGtPlay() throws Exception {
		// JSONObject obj = new JSONObject();
		//		
		// String openid = session().getAttribute("openid") == null ? ""
		// : session().getAttribute("openid").toString();
		// if("".equals(openid)){
		// return;
		// }
		//		
		// Map<String, String> voucherCodeMap =
		// gameService.queryVoucherCodeByOpenid(openid);
		// if(null != voucherCodeMap){
		// obj.put("msg", 0);
		// obj.put("msgcode", voucherCodeMap.get("paycode"));
		// JSONUtils.printObject(obj);
		// return;
		// }
		//		
		// //奖品列表
		// HashMap<String, Double> constans = new HashMap<String, Double>();
		// constans.put("1", 100.0);
		// constans.put("2", 50.0);
		// constans.put("3", 30.0);
		// constans.put("4", 20.0);
		// constans.put("5", 10.0);
		//		
		// //奖品权重
		// ArrayList<Avatar> list = new ArrayList<Avatar>();
		// list.add(new Avatar("1", 10));
		// list.add(new Avatar("2", 15));
		// list.add(new Avatar("3", 20));
		// list.add(new Avatar("4", 25));
		// list.add(new Avatar("5",30));
		//		
		// //根据权重抽中奖品
		// Avatar[] result = RandomWeightUtil.getRandomN(list, 1);
		// int prize = Convert.strToInt(result[0].key, -1);
		// double valMoney = constans.get(result[0].key);
		//		
		// //生成兑换码
		// String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		// String baseN = "1234567890";
		// String paycode = StringUtils.getNoncestr(base, 4)
		// + StringUtils.getNoncestr(baseN, 1)
		// + StringUtils.getNoncestr(base, 4);
		//		
		// long r = gameService.insertVoucherCode(openid, paycode, valMoney,
		// 100001);
		// if(r > 0){
		// obj.put("msg", prize);
		// obj.put("msgcode", paycode);
		// JSONUtils.printObject(obj);
		// }
	}

	/**
	 * 端午摇一摇游戏
	 * 
	 * @throws Exception
	 */
	public String dwGameInit() throws Exception {
		String code = request("code");
		if (null == code || "".equals(code)) {
			return "failed";
		}

		Map<String, String> map = WechatUtils.getOauth2AccessToken(
				WechatConfig.APPID, WechatConfig.APPSECRET, code);
		int errcode = Convert.strToInt(map.get("errcode"), 0);
		String unionid = Convert.strToStr(map.get("unionid"), "");
		if (errcode > 0 || "".equals(unionid)) {
			return "failed";
		}

		session().setAttribute("unionid", unionid);
		// 初始化游戏用户
		Map<String, String> userMap = gameService.queryLotteryUserInfo(unionid,
				100001);
		if (null == userMap) {
			gameService.insertLotteryUser(unionid, 100001, 1);
		}

		return SUCCESS;
	}

	public void dwGamePlay() throws Exception {
		JSONObject obj = new JSONObject();
		HashMap<String, String> rMap = new HashMap<String, String>();
		String unionid = session().getAttribute("unionid") == null ? ""
				: session().getAttribute("unionid").toString();
		if ("".equals(unionid)) {
			return;
		}
		// 参与游戏用户信息
		Map<String, String> userMap = gameService.queryLotteryUserInfo(unionid,
				100001);
		if (userMap == null || userMap.size() <= 0) {
			return;
		}

		int chanceNum = Convert.strToInt(userMap.get("chanceNum"), 0);
		if (chanceNum <= 0) {
			obj.put("errors", "您的游戏机会已用完，分享游戏到朋友圈，可获取一次游戏机会");
			JSONUtils.printObject(obj);
			return;
		}

		// 权重初始化
		List<Map<String, Object>> lotteryGiftList = gameService
				.queryLotteryGift(100001);
		ArrayList<Avatar> list = new ArrayList<Avatar>();
		if (lotteryGiftList != null) {
			for (Map<String, Object> map : lotteryGiftList) {
				String key = map.get("lotteryIndex").toString();
				Double weight = Convert.strToDouble(map.get("weight")
						.toString(), 0);
				String remarks = map.get("remarks").toString();
				list.add(new Avatar(key, weight, remarks));
			}
		} else {
			return;
		}
		// 获取中奖位置
		Avatar[] result = RandomWeightUtil.getRandomN(list, 1);
		int prize = Convert.strToInt(result[0].key, -1);
		String prizeName = Convert.strToStr(result[0].remarks, "");

		// 数据实际操作
		long awardId = gameService.insertLotteryAward(unionid, 100001, prize);
		gameService.updateLotteryUserHasPlayNum(unionid, 100001, 1);

		rMap.put("awardId", awardId + "");
		rMap.put("prizeName", prizeName);
		rMap.put("imgUrl", "");

		obj.put("result", rMap);
		obj.put("success", "success");

		JSONUtils.printObject(obj);
	}

	public void dwGameWxShare() throws Exception {
		String unionid = session().getAttribute("unionid") == null ? ""
				: session().getAttribute("unionid").toString();
		if ("".equals(unionid)) {
			return;
		}

		// 参与游戏用户信息
		Map<String, String> userMap = gameService.queryLotteryUserInfo(unionid,
				100001);
		if (userMap == null || userMap.size() <= 0) {
			return;
		}
		// 增加用户游戏机会
		int hasPlayNum = Convert.strToInt(userMap.get("hasPlayNum"), 0);
		if (hasPlayNum < 3) {
			gameService.updateLotteryUserChanceNum(unionid, 100001);
		}
	}

	public void dwGameGetlucky() throws Exception {
		String unionid = session().getAttribute("unionid") == null ? ""
				: session().getAttribute("unionid").toString();
		if ("".equals(unionid)) {
			return;
		}
		JSONObject obj = new JSONObject();
		String mobilePhone = Convert.strToStr(paramMap.get("phoneNum"), null);
		long awardId = Convert.strToLong(paramMap.get("awardId"), -1L);
		// 参与游戏用户奖励信息
		Map<String, String> awardMap = gameService.queryLotteryAwardById(
				unionid, awardId, 100001);
		Map<String, String> userMap = userService
				.queryUserByUserName(mobilePhone);
		if (null != awardMap) {
			if (null == userMap || userMap.size() <= 0) {
				obj.put("result", "newUser");
				JSONUtils.printObject(obj);
				return;
			} else {
				long userId = Convert.strToLong(userMap.get("id"), -1L);
				int giftType = Convert.strToInt(awardMap.get("giftType"), -1);
				String amount = Convert
						.strToStr(awardMap.get("amount"), "0.00");
				int isPay = Convert.strToInt(awardMap.get("isPay"), 1);
				if (giftType == 3 && isPay != 1) {
					// 兑换共富券
					gameService.insertGofullVoucher(userId, amount, 1, 1,
							"月利宝、季发宝、稳盈宝", 1, "0.0033", 3);
				} else if (giftType != 3) {
					obj.put("result", "entityAward");
					JSONUtils.printObject(obj);
					return;
				}
				// 更新领奖信息
				gameService.updateLotteryAward(awardId, userId);
			}
		}
		obj.put("result", "success");
		JSONUtils.printObject(obj);
	}

	/**
	 * 红包游戏
	 * 
	 * @return
	 * @throws Exception
	 */
	public String redPackInit() throws Exception {
		String unionid = session().getAttribute("unionid") == null ? ""
				: session().getAttribute("unionid").toString();
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return null;
		}
		// 已领到的红包充值到体验金
		if (!"".equals(unionid)) {
			long r = gameService.rechargeRedpack(userId, unionid);
		}
		// 体验金余额
		Map<String, String> availableEliteMap = myHomeService
				.queryAvailableElite(user.getId());
		request().setAttribute("availableEliteMap", availableEliteMap);
		return SUCCESS;
	}

	public String createllredpack() throws Exception {
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return null;
		}
		int env_type = Convert.strToInt(SqlInfusion
				.FilteSqlInfusion(request("packtype")), -1);
		int env_count = Convert.strToInt(SqlInfusion
				.FilteSqlInfusion(request("num")), -1);
		double env_amount = Convert.strToDouble(SqlInfusion
				.FilteSqlInfusion(request("totalflow")), -1d);
		String blessing = Convert.strToStr(SqlInfusion
				.FilteSqlInfusion(request("blessing")), "");
		// 体验金余额
		Map<String, String> availableEliteMap = myHomeService
				.queryAvailableElite(user.getId());
		double eliteAmount = Convert.strToDouble(availableEliteMap
				.get("amount"), -1d);
		BigDecimal d1 = new BigDecimal(env_amount);
		BigDecimal d2 = new BigDecimal(eliteAmount);
		if (env_amount < 0 || d1.compareTo(d2) > 0) {
			return null;
		}
		Map<String, String> autoInfo = userService.queryWchatAutoLoginInfo(user
				.getId());
		String unionid = autoInfo.get("unionid");
		if (null != unionid && "" != unionid) {
			Date date = new Date();
			DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
			DesSecurityUtil des = new DesSecurityUtil();
			String senvKey = des.encrypt(df.format(date) + "|"
					+ autoInfo.get("unionid"));
			long senvId = gameService.createRedpack(userId, d1, 1, env_type,
					env_count, blessing, senvKey, unionid);
			if (senvId < 0) {
				return null;
			} else {
				request().setAttribute("senvKey", senvKey);
				request().setAttribute("env_type", env_type);
				request().setAttribute("env_count", env_count);
				request().setAttribute("env_amount", env_amount);
			}
		}else{
			return null;
		}

		return SUCCESS;
	}

	public String togainllredpack() throws Exception {
		String code = request("code");
		if (null == code || "".equals(code)) {
			return null;
		}

		Map<String, String> map = WechatUtils.getOauth2AccessToken(
				WechatConfig.APPID, WechatConfig.APPSECRET, code);
		int errcode = Convert.strToInt(map.get("errcode"), 0);
		String unionid = Convert.strToStr(map.get("unionid"), "");// 红包领取人unionid
		if (errcode > 0 || "".equals(unionid)) {
			return null;
		}
		// 微信服务号用户信息入库
		userService.updateWechatUserInfoByOauth2(map.get("access_token"), map
				.get("openid"), code);
		session().setAttribute("unionid", unionid);

		String senvKey = SqlInfusion.FilteSqlInfusion(request("state"));
		DesSecurityUtil des = new DesSecurityUtil();
		String[] deParam = des.decrypt(senvKey).split("\\|");
		String sUnionid = deParam[1];// 红包分享人的unionid
		Map<String, String> wechatUserInfoMap = userService
				.queryWechatUserInfo(sUnionid);// 红包分享人的微信用户信息

		request().setAttribute("wechatUserInfoMap", wechatUserInfoMap);
		return SUCCESS;
	}

	public String gainllredpack() throws Exception {
		String senvKey = SqlInfusion.FilteSqlInfusion(request("senvKey"));
		DesSecurityUtil des = new DesSecurityUtil();
		String[] deParam = des.decrypt(senvKey).split("\\|");
		// Long senvId = Convert.strToLong(deParam[0], -1L);
		String sUnionid = deParam[1];// 红包分享人的unionid
		String unionid = session().getAttribute("unionid") == null ? ""
				: session().getAttribute("unionid").toString();
		Map<String, String> m = gameService.queryRedpackByKey(senvKey);
		long senvId = Convert.strToLong(m.get("id"), -1);
		if (!"".equals(unionid)) {
			// 领取红包
			long r = gameService.gainRedpack(senvId, unionid);
			if (r > 0) {
				Map<String, String> recordMap = new HashMap<String, String>();
				if (r == 10002) {
					recordMap.put("envStatus", "2");// 未领过该红包，且红包已领完
				} else {
					recordMap = gameService.queryRedpackRecordById(senvId,
							unionid);
				}

				request().setAttribute("recordMap", recordMap);
			} else {
				return null;
			}
		} else {
			return null;
		}

		Map<String, String> redpackMap = gameService.queryRedpackByKey(senvKey);
		Map<String, String> sWechatInfoMap = userService
				.queryWechatUserInfo(sUnionid);// 红包分享人的微信用户信息

		request().setAttribute("redpackMap", redpackMap);
		request().setAttribute("sWechatInfoMap", sWechatInfoMap);
		return SUCCESS;
	}

	public void gainllredpackList() throws Exception {
		JSONObject obj = new JSONObject();
		String senvKey = SqlInfusion.FilteSqlInfusion(request("senvKey"));

		pageBean.setPageNum(request("pageNo"));
		pageBean.setPageSize(IConstants.PAGE_SIZE_10);
		gameService.queryRedpackRecords(senvKey, pageBean);
		obj.put("pageNo", pageBean.getPageNum());
		obj.put("totalpage", pageBean.getTotalPageNum());
		obj.put("lists", JSONUtils.toJSONArray(pageBean.getPage()));
		JSONUtils.printObject(obj);
	}

	public String myredpacklist() throws Exception {
		String unionid = session().getAttribute("unionid") == null ? ""
				: session().getAttribute("unionid").toString();
		if (!"".equals(unionid)) {
			Map<String, String> wechatInfoMap = userService
					.queryWechatUserInfo(unionid);
			Map<String, String> gainRpStatisticsMap = gameService
					.queryGainRpStatistics(unionid);
			Map<String, String> shareRpStatisticsMap = gameService
					.queryShareRpStatistics(unionid);
			request()
					.setAttribute("shareRpStatisticsMap", shareRpStatisticsMap);
			request().setAttribute("gainRpStatisticsMap", gainRpStatisticsMap);
			request().setAttribute("wechatInfoMap", wechatInfoMap);
		}

		return SUCCESS;
	}

	public void userRedpackList() throws Exception {
		JSONObject obj = new JSONObject();
		pageBean.setPageNum(request("pageNo"));
		pageBean.setPageSize(IConstants.PAGE_SIZE_10);
		int stype = Convert.strToInt(SqlInfusion
				.FilteSqlInfusion(request("stype")), -1);// 1:发出的红包 2：领取的红包
		String unionid = session().getAttribute("unionid") == null ? ""
				: session().getAttribute("unionid").toString();
		if (!"".equals(unionid)) {
			if (stype == 1) {
				gameService.queryShareRpDetail(unionid, pageBean);
			} else if (stype == 2) {
				gameService.queryGainRpDetail(unionid, pageBean);
			}
		}
		obj.put("pageNo", pageBean.getPageNum());
		obj.put("totalpage", pageBean.getTotalPageNum());
		obj.put("lists", JSONUtils.toJSONArray(pageBean.getPage()));
		JSONUtils.printObject(obj);
	}

	public String showMyRedpackList() throws Exception {
		String unionid = session().getAttribute("unionid") == null ? ""
				: session().getAttribute("unionid").toString();
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return null;
		}
		// 已领到的红包充值到体验金
		long r = gameService.rechargeRedpack(userId, unionid);
		// 体验金余额
		Map<String, String> availableEliteMap = myHomeService
				.queryAvailableElite(user.getId());
		request().setAttribute("availableEliteMap", availableEliteMap);

		Map<String, String> lastEliteProduct = myHomeService
				.queryLastEliteProduct();// 体验金理财项目

		request().setAttribute("availableEliteMap", availableEliteMap);
		request().setAttribute("lastEliteProduct", lastEliteProduct);
		return SUCCESS;
	}

	public String redpackRechargeList() throws Exception {
		String unionid = session().getAttribute("unionid") == null ? ""
				: session().getAttribute("unionid").toString();
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return null;
		}
		if (!"".equals(unionid)) {
			Map<String, String> wechatInfoMap = userService
					.queryWechatUserInfo(unionid);
			// 体验金余额
			Map<String, String> availableEliteMap = myHomeService
					.queryAvailableElite(user.getId());
			request().setAttribute("availableEliteMap", availableEliteMap);
			request().setAttribute("wechatInfoMap", wechatInfoMap);
		}
		return SUCCESS;
	}
	
	/**
	 * 每日签到
	 */
	public String signToday() throws Exception {
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return null;
		}
		
		Map<String, String> map = myHomeService.signToday(user.getId());
		long r = Convert.strToLong(map.get("ret"), -1);
		if(r <= 0){
			return null;
		}
		Map<String, String> recordMap  = myHomeService.queryMySignRecord(user.getId());
		request().setAttribute("recordMap", recordMap);
		
		Map<String,String> autoMap = userService.queryWchatAutoLoginInfo(userId);
		if(null != autoMap ){
			String unionid = Convert.strToStr(autoMap.get("unionid"), "");
			if (!"".equals(unionid) && r > 0) {
				Map<String, String> wechatInfoMap = userService
						.queryWechatUserInfo(unionid);
				String openid = Convert.strToStr(autoMap.get("openid"), "");
				request().setAttribute("wechatInfoMap", wechatInfoMap);
				//签到成功通知
				
			}
		}
		return SUCCESS;
	}
}
